<template>
  <el-container style="min-height: 100vh">
    <el-aside
      :width="sideWidth + 'px'"
      style="box-shadow: 2px 0 6px rgb(0 21 41)"
    >
      <el-menu
        :default-openeds="['1', '3']"
        style="min-height: 100%; overflow-x: hidden"
        background-color="rgb(48, 65, 86)"
        text-color="#fff"
        active-text-color="#ffd04b"
        :collapse-transition="false"
        :collapse="isCollapse"
      >
        <div style="height: 60px; line-height: 60px; text-align: center">
          <img
            src="@/assets/logo.png"
            alt=""
            style="width: 20px; position: relative; top: 5px; right: 5px"
          />
          <b style="color: white" v-show="logoTextShow">后台管理系统</b>
        </div>
        <el-submenu index="1">
          <template slot="title">
            <i class="el-icon-message"></i>
            <span slot="title">后台主页</span>
          </template>
          <!-- <el-menu-item index="1-0" ><router-link class="routerto" to="/">后台管理主页</router-link></el-menu-item> -->
          <el-menu-item index="1-1"
            ><router-link class="routerto" to="/goodsManage"
              >商品后台管理</router-link
            ></el-menu-item
          >
          <el-menu-item index="1-2"
            ><router-link class="routerto" to="/user"
              >用户后台管理</router-link
            ></el-menu-item
          >
          <el-menu-item index="1-2"
            ><router-link class="routerto" to="/order"
              >订单后台管理</router-link
            ></el-menu-item
          >
          <el-menu-item @click="logout" id="logOut">退出登录</el-menu-item>
        </el-submenu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header
        style="
          font-size: 12px;
          border-bottom: 1px solid #ccc;
          line-height: 60px;
          display: flex;
        "
      >
        <div style="flex: 1; font-size: 20px">
          <span
            :class="collapseBtnClass"
            style="cursor: pointer"
            @click="collapse"
          ></span>
        </div>
      </el-header>

      <el-main>
        <div style="margin-bottom: 30px">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div style="margin: 10px 0">
          <el-input
            style="width: 200px"
            placeholder="请输入用户昵称"
            suffix-icon="el-icon-search"
            v-model="nickName"
          ></el-input>
          <el-input
            style="width: 200px"
            placeholder="请输入用户电话号码"
            suffix-icon="el-icon-position"
            class="ml-5"
            v-model="phone"
          ></el-input>
          <el-input
            style="width: 200px"
            placeholder="请输入用户管理权限"
            suffix-icon="el-icon-position"
            class="ml-5"
            v-model="userRole"
          ></el-input>
          <el-input
            style="width: 200px"
            placeholder="请输入用户住址"
            suffix-icon="el-icon-position"
            class="ml-5"
            v-model="address"
          ></el-input>
          <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
          <el-button type="warning" @click="reset">重置</el-button>
          <el-popconfirm
            class="ml-5"
            confirm-button-text="确定"
            cancel-button-text="我再想想"
            icon="el-icon-info"
            icon-color="red"
            title="您确定批量删除这些数据吗？"
            @confirm="delBatch"
          >
            <el-button type="danger" slot="reference"
              >批量删除 <i class="el-icon-remove-outline"></i
            ></el-button>
          </el-popconfirm>
        </div>

        <el-table
          :data="tableData"
          border
          stripe
          :header-cell-class-name="headerBg"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="userId"
            label="用户编号"
            width="70"
          ></el-table-column>
          <el-table-column
            prop="nickName"
            label="用户昵称"
            width="70"
          ></el-table-column>
          <el-table-column
            prop="email"
            label="用户注册邮箱"
            width="140"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="用户手机号"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="用户状态"
            width="70"
          ></el-table-column>
          <el-table-column prop="userRole" label="管理权限"></el-table-column>
          <el-table-column prop="address" label="用户地址"></el-table-column>
          <el-table-column prop="createTime" label="注册时间"></el-table-column>
          <el-table-column
            prop="updateTime"
            label="用户修改信息时间"
          ></el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                slot="reference"
                @click="doActive(scope.row.userId)"
                >激活 <i class="el-icon-remove-outline"></i
              ></el-button>
              <el-button
                type="primary"
                slot="reference"
                @click="doFreeze(scope.row.userId)"
                >冻结 <i class="el-icon-remove-outline"></i
              ></el-button>
              <el-popconfirm
                class="ml-5"
                confirm-button-text="给我删！"
                cancel-button-text="再让我想想呗"
                icon="el-icon-info"
                icon-color="red"
                title="您确定删除吗？"
                @confirm="del(scope.row.userId)"
              >
                <el-button type="danger" slot="reference"
                  >删除 <i class="el-icon-remove-outline"></i
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[3, 5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
// import request from "@/utils/request";
import router from "../../router";
export default {
  name: "ManageUser",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 3,
      userName: "",
      phone: "",
      userRole: "",
      address: "",

      form: {},
      multipleSelection: [],
      msg: "hello thh",
      collapseBtnClass: "el-icon-s-fold",
      isCollapse: false,
      sideWidth: 200,
      logoTextShow: true,
      headerBg: "headerBg",
    };
  },
  created() {
    // 请求分页查询数据
    this.load();
  },
  mounted() {
    this.cheackAdmin();
  },
  methods: {
      //倒计时三秒跳转到后台首页
      countDown() {
      const TIME_COUNT = 3;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.timer = setInterval(() => {
          if (this.count > 1 && this.count <= TIME_COUNT) {
            //限制倒计时区间
            this.count--;
          } else {
            clearInterval(this.timer); //删除定时器
            this.timer = null;
            //跳转的页面写在此处
            router.push("/adminpage/login");
          }
        }, 1000);
      }
    },
    cheackAdmin() {
      this.$axios
        .get("/admin/index", {
          headers: {
            "x-access-token": localStorage.getItem("x-access-token"),
          },
        })
        .then((res) => {
          console.log(res);
          if (
            res.data.code == 401 &&
            "用户不存在！" == res.data.extend.result
          ) {
            this.$message.error("请先登录再访问后台");
            router.push("/adminpage/login");
          } else if (
            res.data.code == 401 &&
            "登录失败，该用户没有权限" == res.data.extend.result
          ) {
            this.$message.error("登录失败，该用户不是管理员");
            router.push("/adminpage/login");
          } else if (
            res.data.code == 401 &&
            "该用户已被锁定,暂时无法登录！" == res.data.extend.result
          ) {
            this.$message.error("登录失败，该用户不是管理员");
            router.push("/adminpage/login");
          } else if (
            res.data.code == 200 &&
            "登陆成功" == res.data.extend.result
          ) {
            this.$message({
              message: "管理员你好，欢迎来到后台管理页面",
              type: "success",
            });
          }
        });
    },
    //时间转换(js将 “2021-07-06T06:23:57.000+00:00” 转换为年月日时分秒)
    transformTimestamp(timestamp) {
      let a = new Date(timestamp).getTime();
      const date = new Date(a);
      const Y = date.getFullYear() + "-";
      const M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      const D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + "  ";
      const h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      const m =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      // const s = date.getSeconds(); // 秒
      const dateString = Y + M + D + h + m;
      // console.log('dateString', dateString); // > dateString 2021-07-06 14:23
      return dateString;
    },
    collapse() {
      // 点击收缩按钮触发
      this.isCollapse = !this.isCollapse;
      if (this.isCollapse) {
        // 收缩
        this.sideWidth = 64;
        this.collapseBtnClass = "el-icon-s-unfold";
        this.logoTextShow = false;
      } else {
        // 展开
        this.sideWidth = 200;
        this.collapseBtnClass = "el-icon-s-fold";
        this.logoTextShow = true;
      }
    },
    load() {
      this.request
        .get("/manage/userPage", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            nickName: this.userName,
            phone: this.phone,
            address: this.address,
            userRole: this.userRole,
          },
        })
        .then((res) => {
          console.log(res.records[0]);
          for (var i = 0; i < res.records.length; i++) {
            if (res.records[i].status == 1) {
              res.records[i].status = "正常";
            }
            if (res.records[i].status == 0) {
              res.records[i].status = "冻结";
            }
            res.records[i].createTime = this.transformTimestamp(
              res.records[i].createTime
            );
            res.records[i].updateTime = this.transformTimestamp(
              res.records[i].updateTime
            );
          }
          this.tableData = res.records;
          this.total = res.total;
        });
    },
    //退出登录
    logout() {
      var storage = window.localStorage;
      storage.clear();
      this.$message({
        message: "管理员已退出，三秒后回到后台首页",
        type: "success",
      });
      this.countDown();
    },
    del(userId) {
      this.request.delete("/manage/deleteUser/" + userId).then((res) => {
        if (res) {
          this.$message.success("删除成功");
          this.load();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //批量删除
    delBatch() {
      let userIds = this.multipleSelection.map((v) => v.userId); // [{}, {}, {}] => [1,2,3]
      this.request.post("/manage/delUser/batch", userIds).then((res) => {
        if (res) {
          this.$message.success("批量删除成功");
          this.load();
        } else {
          this.$message.error("批量删除失败");
        }
      });
    },
    
    reset() {
      this.userName = "";
      this.phone = "";
      this.address = "";
      this.userRole = "";
      this.load();
    },
    handleSizeChange(pageSize) {
      console.log(pageSize);
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum);
      this.pageNum = pageNum;
      this.load();
    },

    //激活用户
    doActive(tUserId) {
      this.request
        .get("/manage/activate", {
          params: {
            userId: tUserId,
          },
        })
        .then((res) => {
          if (res) {
            this.$message.success("用户激活成功");
            this.load();
          } else {
            this.$message.error("用户激活失败");
            this.load();
          }
        });
    },
    doFreeze(tUserId) {
      this.request
        .get("/manage/freeze", {
          params: {
            userId: tUserId,
          },
        })
        .then((res) => {
          if (res) {
            this.$message.success("用户冻结成功");
            this.load();
          } else {
            this.$message.error("用户冻结失败");
            this.load();
          }
        });
    },
  },
};
</script>

<style>
.headerBg {
  background: #eee !important;
}
.routerto {
  color: #fff;
  text-decoration: none;
}
</style>
